package com.anasoft.os.m2st.doxia.macro;

import java.io.IOException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import org.apache.commons.lang.StringEscapeUtils;

/**
 * Code snippet taken from a specific source file denoted by {@link URL}.
 * 
 * <p>
 * 
 * Each code snippet represents either a continuous data region
 * taken from the source file (<tt>id</tt> is not <tt>null</tt>)
 * or the entire source file contents (<tt>id</tt> is <tt>null</tt>).
 * See {@link BaseMacro#loadSnippet(String, URL, String)} for information
 * about using snippet <tt>id</tt> within your source files.
 * 
 * @see CodeSnippetMacro
 * 
 * @author milan.skuhra
 * @author vojtech.szocs
 */
public class CodeSnippet {

    private static final String TAG_NAME = "pre";
    
    private final String content;
    private final Map<String, String> attributes = new HashMap<String, String>();
    
    /**
     * Creates a new code snippet.
     * 
     * @param id Snippet identifier (can be <tt>null</tt>
     * to include the entire source file contents).
     * @param url Source file {@link URL}.
     * @param encoding Source file encoding.
     * @throws IOException
     */
    public CodeSnippet(String id, URL url, String encoding) throws IOException {
        content = BaseMacro.loadSnippet(id, url, encoding);
    }
    
    /**
     * Sets an attribute to be reflected into the final
     * HTML code for this snippet.
     * 
     * @param name Attribute name.
     * @param value Attribute value.
     */
    public void setAttribute(String name, String value) {
        attributes.put(name, value);
    }
    
    /**
     * Wraps the escaped snippet content in a tag with
     * attributes and returns the resulting HTML code.
     * 
     * @return Snippet HTML code.
     */
    @Override
    public String toString() {
        StringBuilder html = new StringBuilder();
        html.append("<").append(TAG_NAME);
        
        Set<String> attributeNames = attributes.keySet();
        for (String name : attributeNames) {
            html.append(" ").append(name).append("=").append("\"").append(attributes.get(name)).append("\"");
        }
        
        html.append(">")
            .append(StringEscapeUtils.escapeHtml(content))
            .append("</").append(TAG_NAME).append(">");
        
        return html.toString();
    }
    
}
